<template>
  <div>
    <el-form :model="ruleForm"
             status-icon
             :rules="rules"
             ref="ruleForm"
             label-width="100px"
             class="demo-ruleForm">
      <el-form-item label="用户"
                    prop="username">
        <el-input type="text"
                  v-model="ruleForm.username"
                  autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码"
                    prop="pass">
        <el-input type="password"
                  v-model="ruleForm.pass"
                  autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"
                   @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import md5 from "md5";
export default {
  props: ["userRules"],
  data () {
    const { username, password } = this.userRules;
    var validatePass = (rule, value, callback) => {
      if (value.trim() === "") {
        callback(new Error("请输入密码"));
      } else {
        if (value.trim().length < password.min) {
          callback(new Error(`密码不小于${password.min}位`));
        }
        callback();
      }
    };
    var validateUsername = (rule, value, callback) => {
      if (value.trim() === "") {
        callback(new Error("请输入账号！"));
      } else if (value.trim().length < username.min) {
        callback(new Error(`账号不小于${username.min}位`));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        pass: "",
        username: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        username: [{ validator: validateUsername, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapActions(["actUser"]),
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 先把要传的参数进行格式化
          let { pass: password, username } = this.ruleForm;
          password = md5(password);
          this.actUser({ password, username, state: 1 }).then((res) => {
            if (res.code) {
              // 路由跳转
              this.$router.replace("/layout");
            } else {
              this.$message('账号或密码错误')
            }
          });
        } else {
          return false;
        }
      });
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style></style>
